#pragma once

// -----------------------------------------------------------------------------

#include <Windows.h>
#include <Winbase.h>

#include "Win32.Diagnostics.Result.h"
#include "Win32.String.h"

namespace Kif
{
namespace Win32
{
namespace IO
{

class DirectoryCursor
{
private:

   Kif::Win32::Diagnostics::Result lastResult;

   HANDLE  cursorHandle;        // cursor handle
   Kif::Win32::String dirPath;  // directory path
   WIN32_FIND_DATA dirEntry;    // File information

   bool   getFirstEntry;
   bool   cycle ;               // true to cycle after end of last dir entry

public:

   long Count;
   bool IgnoreDottedEntries;

   /// <summary>reset directory cursor</summary>
   void Reset()
   {
      getFirstEntry = true ;
      Count = 0 ;
   }  // end of GetFirstEntry

   DirectoryCursor()
   {
      cursorHandle = INVALID_HANDLE_VALUE;
      IgnoreDottedEntries = true;
      cycle   = false;

      Reset();
   }  // end of DirectoryInfo (ctor)

  ~DirectoryCursor()
   {
      Close();
   }  // end of DirectoryInfo (dtor)

   bool IsDirectory()
   {
      return(dirEntry.dwFileAttributes &
         FILE_ATTRIBUTE_DIRECTORY) ? true : false;
   }  // end of IsDirectory

   bool Open(TCHAR *path)
   {
      if (path == NULL)
         return(false);
      dirPath.Copy(path);
      Reset();
      return(true);
   }  // end of Open

   bool Open(Kif::Win32::String *path)
   {
      if (path == NULL)
         return(false);
      return(Open(path->GetBuffer()));
   }  // end of Open

   bool Open(Kif::Win32::String &path)
   {
      return(Open(path.GetBuffer()));
   }  // end of Open

   TCHAR *GetCurrentDirectoryEntryName()
   {
      return(dirEntry.cFileName);
   }  // end of GetCurrentDirectoryEntryName

   bool Next();
   inline bool EndOfDirectory()
   {
      return((lastResult.ErrorNo == ERROR_NO_MORE_FILES) ||
             (cursorHandle == INVALID_HANDLE_VALUE));
   }  // end of EndOfDirectory

   /// <summary>close directory cursor</summary>
   inline void Close()
   {
      if (cursorHandle != INVALID_HANDLE_VALUE)
         FindClose(cursorHandle);
      cursorHandle = INVALID_HANDLE_VALUE;
   }  // end of 

}  ;  // end of DirectoryCursor

}  // end of Kif::Win32::IO
}  // end of Kif::Win32
}  // end of Kif

